<template>
  <div ref="playerContainer" class="h265-player-container">
    <div :id="playerId" class="h265-player"></div>
    <div v-if="!isPlaying && !isLoading" class="no-video-message">
      暂无视频源
    </div>
    <div v-if="isLoading" class="loading-message">
      正在加载视频...
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'

// Props
const props = defineProps({
  width: {
    type: Number,
    default: 800
  },
  height: {
    type: Number,
    default: 450
  }
})

// 响应式数据
const playerContainer = ref(null)
const playerId = ref(`h265-player-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`)
const isPlaying = ref(false)
const isLoading = ref(false)
const currentPlayer = ref(null)

// H265播放器token
const token = "base64:QXV0aG9yOmNoYW5neWFubG9uZ3xudW1iZXJ3b2xmLEdpdGh1YjpodHRwczovL2dpdGh1Yi5jb20vbnVtYmVyd29sZixFbWFpbDpwb3JzY2hlZ3QyM0Bmb3htYWlsLmNvbSxRUTo1MzEzNjU4NzIsSG9tZVBhZ2U6aHR0cDovL3h2aWRlby52aWRlbyxEaXNjb3JkOm51bWJlcndvbGYjODY5NCx3ZWNoYXI6bnVtYmVyd29sZjExLEJlaWppbmcsV29ya0luOkJhaWR1"

// 创建播放器
const createPlayer = (url, autoplay = true, volume = 1) => {
  console.log('H265Player: 创建播放器，URL:', url)
  
  if (!url) {
    console.error('H265Player: URL为空，无法创建播放器')
    return
  }

  // 先销毁现有播放器
  destroyPlayer()

  isLoading.value = true

  nextTick(() => {
    try {
      if (!window.new265webjs) {
        console.error('H265Player: H265播放器库未加载')
        isLoading.value = false
        return
      }

      const config = {
        type: 'flv', // 明确指定为FLV流
        player: playerId.value,
        width: props.width,
        height: props.height,
        token: token,
        extInfo: {
          coreProbePart: 0.4,
          probeSize: 8192,
          ignoreAudio: 0,
          moovStartFlag: false,
          rawFps: 25,
          autoCrop: false,
          core: 1
        }
      }

      console.log('H265Player: 创建播放器配置:', config)
      
      currentPlayer.value = new window.new265webjs(url, config)
      
      // 设置事件回调
      currentPlayer.value.onReadyShowDone = () => {
        console.log('H265Player: 准备显示完成')
        isLoading.value = false
        if (autoplay) {
          const result = currentPlayer.value.play()
          isPlaying.value = result
          console.log('H265Player: 自动播放结果:', result)
        }
      }

      currentPlayer.value.onLoadFinish = () => {
        console.log('H265Player: 加载完成')
        isLoading.value = false
      }

      currentPlayer.value.onPlayTime = (videoPTS) => {
        // console.log('H265Player: 播放时间:', videoPTS)
      }

      currentPlayer.value.onPlayFinish = () => {
        console.log('H265Player: 播放结束')
        isPlaying.value = false
      }

      // 启动播放器
      currentPlayer.value.do()
      
    } catch (error) {
      console.error('H265Player: 创建播放器失败:', error)
      isLoading.value = false
    }
  })
}

// 播放
const play = () => {
  if (currentPlayer.value) {
    try {
      const result = currentPlayer.value.play()
      isPlaying.value = result
      console.log('H265Player: 播放结果:', result)
      return result
    } catch (error) {
      console.error('H265Player: 播放失败:', error)
      return false
    }
  }
  return false
}

// 暂停
const pause = () => {
  if (currentPlayer.value) {
    try {
      currentPlayer.value.pause()
      isPlaying.value = false
      console.log('H265Player: 已暂停')
    } catch (error) {
      console.error('H265Player: 暂停失败:', error)
    }
  }
}

// 停止
const stop = () => {
  if (currentPlayer.value) {
    try {
      currentPlayer.value.pause()
      isPlaying.value = false
      console.log('H265Player: 已停止')
    } catch (error) {
      console.error('H265Player: 停止失败:', error)
    }
  }
}

// 销毁播放器
const destroyPlayer = () => {
  if (currentPlayer.value) {
    try {
      console.log('H265Player: 销毁播放器')
      currentPlayer.value.release()
      currentPlayer.value = null
      isPlaying.value = false
      isLoading.value = false
    } catch (error) {
      console.error('H265Player: 销毁播放器失败:', error)
    }
  }
}

// 关闭播放器（别名）
const closePlayer = () => {
  destroyPlayer()
}

// 切换视频源
const changeVideo = (url) => {
  console.log('H265Player: 切换视频源:', url)
  createPlayer(url)
}

// 设置音量
const setVolume = (volume) => {
  if (currentPlayer.value) {
    try {
      currentPlayer.value.setVoice(volume)
      console.log('H265Player: 设置音量:', volume)
    } catch (error) {
      console.error('H265Player: 设置音量失败:', error)
    }
  }
}

// 截图
const screenshot = () => {
  if (currentPlayer.value) {
    try {
      currentPlayer.value.screenshot()
      console.log('H265Player: 截图完成')
    } catch (error) {
      console.error('H265Player: 截图失败:', error)
    }
  }
}

// 获取播放状态
const getIsPlaying = () => {
  if (currentPlayer.value) {
    try {
      return currentPlayer.value.isPlaying()
    } catch (error) {
      console.error('H265Player: 获取播放状态失败:', error)
      return false
    }
  }
  return false
}

// 生命周期
onMounted(() => {
  console.log('H265Player: 组件挂载，播放器ID:', playerId.value)
  console.log('H265Player: 检查H265库是否加载:', typeof window.new265webjs)
  
  if (!window.new265webjs) {
    console.error('H265Player: H265播放器库未加载，请检查script标签')
  } else {
    console.log('H265Player: H265播放器库已正确加载')
  }
})

onUnmounted(() => {
  console.log('H265Player: 组件卸载')
  destroyPlayer()
})

// 暴露方法给父组件
defineExpose({
  createPlayer,
  play,
  pause,
  stop,
  closePlayer,
  changeVideo,
  setVolume,
  screenshot,
  isPlaying: getIsPlaying,
  destroy: destroyPlayer
})
</script>

<style scoped>
.h265-player-container {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.h265-player {
  width: 100%;
  height: 100%;
}

.no-video-message,
.loading-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #08979C;
  font-size: 18px;
  z-index: 10;
}

.loading-message {
  color: #1890ff;
}
</style>